package cluster

import(
	"github.com/sniperHW/kendynet"
	//"github.com/sniperHW/kendynet/rpc"
	"github.com/sniperHW/kendynet/socket/stream_socket/tcp"
	//"sanguo/codec/ss"
	//"sanguo/common"
	"time"
	"fmt"
)


func dialError(end *endPoint,session kendynet.StreamSession,err error) {
	//记录日志
	Errorf("%s dial error:%s\n",end.toPeerID().ToString(),err.Error())
	if nil != session {
		session.Close(err.Error(),0)
	}
	if nil == end.conn {
		end.pendingMsg = end.pendingMsg[0:0]
		go func() {
			pendingCall := end.pendingCall
		  	end.pendingCall = end.pendingCall[0:0]
		  	for _,r := range pendingCall {  
		  		r.cb(nil,err)
		    } 		
		}()
	}
	end.dialing = false
}

func dialOK(end *endPoint,session kendynet.StreamSession) {
	onEstablishClient(end,session)
	end.dialing = false
}


func dialRet(end *endPoint,session kendynet.StreamSession,err error) {
	if nil != session {
		//连接成功
		login(end,session)
	} else {
		//连接失败
		dialError(end,session,err)		
	}
}

func dial(end *endPoint) {
	//发起异步Dial连接

	if !end.dialing {

		end.dialing = true

		Infof("dial %s\n",end.toPeerID().ToString())

		go func(){
			client,err := tcp.NewConnector("tcp4",fmt.Sprintf("%s:%d",end.ip,end.port))
			if err != nil {
				queue.PostNoWait(func () {
					dialRet(end,nil,err)
				})
			} else {
		    	session,err := client.Dial(time.Second * 3)
				queue.PostNoWait(func () {
					dialRet(end,session,err)
				})
		    }
		}()
	}
}